<?php


namespace App\Services;


use App\Libs\TokenGenerator;
use App\Models\User;

class AuthService extends BaseService
{
    public function getUserByToken($token)
    {
        $found = User::where('token', $token)->get();

        if($found->isEmpty()){
            return false;
        }
        return $found->first();
    }

    public function login($phone, $password)
    {
        $found = User::where('phone', $phone)->get();
        if($found->isEmpty()) {
            return null;
        }

        $user = $found->first();
        if(!\Hash::check($password, $user->password)) {
            return null;
        }

        $token = TokenGenerator::generate();
        $user->token = $token;
        $user->save();
        return $user;
    }

    public function logout($token)
    {
        $found = User::where('token', $token)->get();
        if($found->isEmpty()) {
            return false;
        }

        $user = $found->first;
        if($user->token != $token) {
            return false;
        }

        $user->token = '';
        $user->save();
        return $user;
    }
}